//
//  OrderPayViewController.m
//  WorkNest
//
//  Created by qbm360 on 15/7/14.
//  Copyright (c) 2015年 nest. All rights reserved.
//

#import "OrderPayViewController.h"
#import "Order.h"
#import "DataSigner.h"
#import <AlipaySDK/AlipaySDK.h>
#import "APAuthV2Info.h"
#import "WXApiObject.h"
#import "WXApi.h"
#import "payRequsestHandler.h"
#import "PayModel.h"

@interface OrderPayViewController () <UITextFieldDelegate>

@property (nonatomic, strong) NSArray *array;
@property (nonatomic, strong) NSArray *payArray;
@property (nonatomic, strong) UIButton *button;
//@property (nonatomic, assign) BOOL ifSelected;
@property (nonatomic, strong) NSString *discount;
@property (nonatomic, assign) BOOL ifAllIntegral;
@property (nonatomic, strong) NSString *sumMoney;
@property (nonatomic, strong) NSIndexPath *indexPath; // 实际支付金额的位置
@property (nonatomic, strong) NSString *useDiscount;
@property (nonatomic, strong) PayModel *payModel;

@end

@implementation OrderPayViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"订单支付";
    self.payArray = @[@{@"image":@"aliPay", @"name":@"支付宝客户端支付", @"info":@"推荐已安装支付宝客户端的用户使用"}, @{@"image":@"weChat", @"name":@"微信支付", @"info":@"推荐已安装微信客户端的用户使用"}, @{@"image":@"unionPay", @"name":@"银联安全支付", @"info":@""}];
//    self.ifSelected = NO;
    self.sumMoney = @"";
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.barStyle = UIBarStyleDefault;
    [self.navigationController.navigationBar setBackgroundImage:nil forBarMetrics:UIBarMetricsDefault];
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName: [UIUtil colorWithHexString:appFontColor]}];
    [self requestData];
}

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    if ([self.tableView respondsToSelector:@selector(setSeparatorInset:)]) {
        [self.tableView setSeparatorInset:UIEdgeInsetsZero];
    }
    if ([self.tableView respondsToSelector:@selector(setLayoutMargins:)]) {
        [self.tableView setLayoutMargins:UIEdgeInsetsZero];
    }
}

- (void)requestData {
    NSDictionary *dic = @{@"userName":[UserModel sharedInstance].userName, @"token":[UserModel sharedInstance].userToken,@"toPayId":self.toPayId==nil?@"":self.toPayId};
    [RequestData queryToPayListParameters:[UIUtil toJsonString:dic] withBlock:^(NSArray *jsonArray, NSString *msg, NSError *error) {
        if (error) {
            if ([msg isEqualToString:@"9001"] || [msg isEqualToString:@"9002"]) {
                [UIUtil tokenOverdue:self msg:msg];
            } else {
                [[ESHUDView sharedInstance] showErrorMessage:msg==nil?@"请求失败":msg dismissBlock:nil];
            }
        } else {
            self.payModel = jsonArray[0];
        }
    }];
}

- (void)setPayModel:(PayModel *)payModel {
    _payModel = payModel;
    NSDictionary *dic = @{@"userName":[UserModel sharedInstance].userName, @"token":[UserModel sharedInstance].userToken};
    [RequestData getUserDetail:[UIUtil toJsonString:dic] withBlock:^(UserInfoModel *model, NSString *msg, NSError *error) {
        if (error) {
            if ([msg isEqualToString:@"9001"] || [msg isEqualToString:@"9002"]) {
                [UIUtil tokenOverdue:self msg:msg];
            } else {
                [[ESHUDView sharedInstance] showErrorMessage:msg==nil?@"请求失败":msg dismissBlock:nil];
            }
        } else {
            self.discount = model.integral;
            self.array = @[@"订单总金额",@"支付内容",@"支付金额", [NSString stringWithFormat:@"可用积分抵￥%.2f",[self.discount floatValue]], @"请支付"];
            [self.tableView reloadData];
        }
    }];
}

#pragma mark - Table view data source
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
        [cell setSeparatorInset:UIEdgeInsetsZero];
    }
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 6;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *payCellIdentifier1 = @"payCell1";
    static NSString *payCellIdentifier2 = @"payCell2";
    if (indexPath.section != 5) {
        UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:payCellIdentifier1];
        [cell.textLabel setTextColor:[UIUtil colorWithHexString:appFontColor]];
        cell.textLabel.text = [self.array objectAtIndex:indexPath.section];
        cell.textLabel.font = [UIFont systemFontOfSize:14];
        if (indexPath.section == 1) {
            cell.detailTextLabel.font = [UIFont systemFontOfSize:11];
        } else {
            cell.detailTextLabel.font = [UIFont systemFontOfSize:15];
        }
        switch (indexPath.section) {
            case 0: {
                cell.detailTextLabel.text = _payModel.totalAmount;
                break;
            }
            case 1: {
                UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(80, 0, SCREEN_WIDTH-90, 44)];
                label.text = _payModel.payContent;
                label.font = [UIFont systemFontOfSize:13];
                label.textColor = [UIUtil colorWithHexString:@"#7b7c80"];
                [cell.contentView addSubview:label];
                label.numberOfLines = 0;
                break;
            }
            case 2: {
                cell.detailTextLabel.text = _payModel.remain;
                break;
            }
            case 3: {
                UITextField *text = [[UITextField alloc] initWithFrame:CGRectMake(0, 7, 60, 28)];
                text.delegate = self;
                text.layer.borderWidth = 1;
                if ([_payModel.remain floatValue] > [self.discount floatValue]) {
                    text.text = self.discount;
                } else {
                    text.text = _payModel.remain;
                }
                self.useDiscount = text.text;
                text.textAlignment = NSTextAlignmentRight;
                text.font = [UIFont systemFontOfSize:14];
                text.textColor = [UIUtil colorWithHexString:@"#aaaaaa"];
                text.layer.borderColor = [[UIUtil colorWithHexString:@"#bdbaba"] CGColor];
                cell.accessoryView = text;
                break;
            }
            case 4: {
                _indexPath = indexPath;
                if ([_payModel.remain floatValue] > [self.discount floatValue]) {
                    cell.detailTextLabel.text = [NSString stringWithFormat:@"%.2f",[_payModel.remain floatValue] - [self.discount floatValue]];
                    self.sumMoney = cell.detailTextLabel.text;
                    _ifAllIntegral = NO;
                    self.tableView.tableFooterView.hidden = YES;
                } else {
                    cell.detailTextLabel.text = @"0.00";
                    self.sumMoney = @"0";
                    _ifAllIntegral = YES;
                    [self tableFootview];
                }
                break;
                 }
            default:
                break;
        }
        return cell;
    } else {
        UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:payCellIdentifier2];
        [cell.textLabel setTextColor:[UIUtil colorWithHexString:appFontColor]];
        [cell.detailTextLabel setTextColor:[UIUtil colorWithHexString:@"#aaaaaa"]];
        cell.imageView.image = [UIImage imageNamed:[[self.payArray objectAtIndex:indexPath.row] valueForKey:@"image"]];
        cell.textLabel.text = [[self.payArray objectAtIndex:indexPath.row] valueForKey:@"name"];
        cell.detailTextLabel.text = [[self.payArray objectAtIndex:indexPath.row] valueForKey:@"info"];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        return cell;
    }
}

#pragma mark - Table view delegate
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 11;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return indexPath.section == 5 ? 50 : 44;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.section == 5 && indexPath.row == 0) {
        if (_ifAllIntegral) {
            [[ESHUDView sharedInstance] showErrorMessage:@"积分足够支付全额,请点击积分支付付款" dismissBlock:nil];
        } else {
            [self aliPay];
            [ESHUDView showLoading];
        }
    }
}

- (void)tableFootview {
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    [button setBackgroundImage:[UIImage imageNamed:@"submitButton"] forState:UIControlStateNormal];
    [button setTitle:@"积分支付" forState:UIControlStateNormal];
    [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    button.frame = CGRectMake((SCREEN_WIDTH-74)/2, 8, 74, 32);
    [button addTarget:self action:@selector(integralPay) forControlEvents:UIControlEventTouchUpInside];
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 48)];
    [view addSubview:button];
    self.tableView.tableFooterView = view;
}

- (void)integralPay {
    [self submitPayInfo:@"1"];
    [ESHUDView showLoading];
}

- (void)aliPay {
    /*
     *商户的唯一的parnter和seller。
     *签约后，支付宝会为每个商户分配一个唯一的 parnter 和 seller。
     */
    /*=======================需要填写商户app申请的===================================*/
    NSString *partner = @"2088021129685842";
    NSString *seller = @"gongckj@aliyun.com";
    NSString *privateKey = @"MIICdQIBADANBgkqhkiG9w0BAQEFAASCAl8wggJbAgEAAoGBAK06dGcZM2cqA2LsIi8ZNyVnibpJ59ONJAEv6xTo3tKwzEKLLHO14i2MF/r+Kdp8ijYBDFoYlkxfsJH0YzvL/kJEG24vXXIKsvZf5lRj0JoE9H+Fd8xc5nY0tHoW+7fgmBu3qpVAuRe1C8C78tQusu0LL3+M39U70CHz6/cHZRo/AgMBAAECgYBA/9ETqmoWSLZylOYSxCRkHaCZTQf24lvjMibEdsi9R+etBGnOlS3kJ1AMNvhfaiG2N9h5qgYjbDhl28yscFPbzPj2FwbSwsq+7WyIT6gsTFEv3QmuVST2f1koMcJThyUyile9kaOgjjDAW0Sl8wWCYhsSkucdk+5KxH/1t77/sQJBAOUBq8KG1CxpNhboNrYA7qg6At88ZFHeouJRQLh/lV/z/SUutrVQWfdHjePDb+7LRTtn5c+Bz/LzWtqLjsJX43cCQQDBpam7ZT17tSLry3Oiis49+KpzzyqibLct9IE40KHeJj2+1ts66iEBaM+qS+HifQdkic7qdSMOwN7uNTZwSeF5AkA5bOvXQdwerttjbyOZDC7MfI+PzyMQ7JVHzzw9h7C7eQF3u3kRim6k9Yp9HNsKtGpN9UXJfTHaKHAV8X0A+u0NAkAW3fQ0H9lp0VMFWyoViKSgJswiDtWvBn1/HL9hsSlcLVHfRknvJBSvsOvM5VcQQslrsuZPQ3PXWyk4IeqCygapAkAv1vSwDtG2eBEVY95UKsNY/dGxwinrqlxED0IX7RuLBswnRBFPEML8UWdggTFmYD8tFrON1ZhbRanlLyGEWOFo";
    /*============================================================================*/
    //partner和seller获取失败,提示
    if ([partner length] == 0 || [seller length] == 0 || [privateKey length] == 0){
        [[ESHUDView sharedInstance] showErrorMessage:@"缺少partner或者seller或者私钥。" dismissBlock:nil];
        return;
    }
    /*
     *生成订单信息及签名
     */
    //将商品信息赋予AlixPayOrder的成员变量
    Order *order = [[Order alloc] init];
    order.partner = partner;
    order.seller = seller;
    order.tradeNO = _payModel.orderId; //订单ID（由商家自行制定）
    order.productName = _payModel.productName; //商品标题
    order.productDescription = _payModel.payContent; //商品描述
    order.amount = self.sumMoney; //商品价格
//    order.amount = @"100";
    order.notifyURL =  @"http://www.xxx.com"; //回调URL
    
    order.service = @"mobile.securitypay.pay";
    order.paymentType = @"1";
    order.inputCharset = @"utf-8";
    order.itBPay = @"30m";
    order.showUrl = @"m.alipay.com";
    
    //应用注册scheme,在AlixPayDemo-Info.plist定义URL types
    NSString *appScheme = @"gongchao";
    
    //将商品信息拼接成字符串
    NSString *orderSpec = [order description];
    NSLog(@"orderSpec = %@",orderSpec);
    
    //获取私钥并将商户信息签名,外部商户可以根据情况存放私钥和签名,只需要遵循RSA签名规范,并将签名字符串base64编码和UrlEncode
    id<DataSigner> signer = CreateRSADataSigner(privateKey);
    NSString *signedString = [signer signString:orderSpec];
    
    //将签名成功字符串格式化为订单字符串,请严格按照该格式
    NSString *orderString = nil;
    if (signedString != nil) {
        orderString = [NSString stringWithFormat:@"%@&sign=\"%@\"&sign_type=\"%@\"",
                       orderSpec, signedString, @"RSA"];
        
        [[AlipaySDK defaultService] payOrder:orderString fromScheme:appScheme callback:^(NSDictionary *resultDic) {
            if ([[resultDic valueForKey:@"resultStatus"] isEqualToString:@"9000"]) {
//                [[ESHUDView sharedInstance] showSuccessMessage:@"支付成功" dismissBlock:nil];
                NSLog(@"支付成功");
                [self submitPayInfo:@"2"];
            } else {
                [[ESHUDView sharedInstance] showErrorMessage:[resultDic valueForKey:@"memo"] dismissBlock:nil];
                [self requestData];
                NSLog(@"%@",[resultDic valueForKey:@"memo"]);
            }
        }];
    }
}

- (void)submitPayInfo :(NSString *)payWay {
    NSDate *sendDate=[NSDate date];
    NSDateFormatter *dateformatter=[[NSDateFormatter alloc] init];
    [dateformatter setDateFormat:@"YYYY-MM-dd hh:mm:ss"];
    NSString *dateString=[dateformatter stringFromDate:sendDate];
    NSDictionary *dic = @{@"userName":[UserModel sharedInstance].userName,
                             @"token":[UserModel sharedInstance].userToken,
                           @"orderId":_payModel.orderId==nil?@"":_payModel.orderId,
                           @"toPayId":_toPayId==nil?@"":_toPayId,
                            @"payWay":payWay,
                   @"paySerialNumber":_payModel.orderId==nil?@"":_payModel.orderId,
                        @"payContent":_payModel.payContent==nil?@"":_payModel.payContent,
                       @"payUserName":[UserModel sharedInstance].userName,
                        @"payAccount":@"",
                            @"paySum":self.sumMoney,
                           @"paySum1":self.useDiscount,
                           @"payTime":dateString,
                       @"payExplains":@"",
                @"collectionUserName":@"gckj",
                 @"collectionAccount":@"gongckj@aliyun.com",
                            @"remark":@""};
    [RequestData pay:[UIUtil toJsonString:dic] withBlock:^(NSString *msg, NSError *error) {
        if (error) {
            if ([msg isEqualToString:@"9001"] || [msg isEqualToString:@"9002"]) {
                [UIUtil tokenOverdue:self msg:msg];
            } else {
                if ([payWay isEqualToString:@"1"]) {
                [[ESHUDView sharedInstance] showErrorMessage:msg==nil?@"积分支付提交失败":msg dismissBlock:nil];
                } else {
                [[ESHUDView sharedInstance] showErrorMessage:msg==nil?@"支付信息提交失败":msg dismissBlock:nil];
                }
            }
        } else {
            [[ESHUDView sharedInstance] showSuccessMessage:@"支付信息提交成功" dismissBlock:nil];
            UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake((SCREEN_WIDTH-80)/2, 0, 80, 44)];
            label.text = @"支付成功";
            self.tableView.tableFooterView = label;
            self.tableView.userInteractionEnabled = NO;
        }
    }];
}

- (void)textFieldDidEndEditing:(UITextField *)textField {
    if ([textField.text isEqualToString: @""] || textField.text.floatValue == 0) {
        textField.text = @"0.00";
    }
    if ([textField.text floatValue] > [self.discount floatValue]) {
        textField.text = [NSString stringWithFormat:@"%.2f",[self.discount floatValue]];
    }
    if ([textField.text floatValue] > [_payModel.remain floatValue]) {
        textField.text = _payModel.remain;
    }
    self.useDiscount = textField.text;
    if ([textField.text floatValue] > [_payModel.remain floatValue] || [textField.text floatValue] == [_payModel.remain floatValue]) {
        [self tableFootview];
        _ifAllIntegral = YES;
    } else {
        _ifAllIntegral = NO;
        self.tableView.tableFooterView.hidden = YES;
    }
    [self.tableView cellForRowAtIndexPath:_indexPath].detailTextLabel.text = [NSString stringWithFormat:@"%.2f", ([_payModel.remain floatValue] - [textField.text floatValue])];
    self.sumMoney = [NSString stringWithFormat:@"%.2f", ([_payModel.remain floatValue] - [textField.text floatValue])];
}

- (void)textFieldDidBeginEditing:(UITextField *)textField {
    if ([textField.text isEqualToString:@"0.00"]) {
        textField.text = @"";
    }
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    [self.view endEditing:YES];
}

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 30)];
    textField.inputAccessoryView = view;
    view.backgroundColor = [UIColor whiteColor];
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.frame = CGRectMake(SCREEN_WIDTH - 40, 0, 40, 30);
    [btn setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    [btn setTitle:@"完成" forState: UIControlStateNormal];
    [btn addTarget:self action:@selector(checkButton) forControlEvents:UIControlEventTouchUpInside];
    [view addSubview:btn];
    [textField reloadInputViews];
    return YES;
}

- (void)checkButton {
    [self.view endEditing:YES];
}

@end
